<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
        class="search-item border-bottom"
        v-for="item of list"
        :key="item.id"
        @click="handleCityClick(item.name)">{{item.name}}</li>
        <li
        class="search-item border-bottom"
        v-show="nocity">没有找到对应的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
  import Bscroll from 'better-scroll'
  export default {
    name: 'citySearch',
    props: {
      allCity: Object
    },
    data (){
      return {
        keyword: '',
        list: [],
        timer: null
      }
    },
    methods: {
      handleCityClick (city){
        // this.$store.dispatch('changeCity', city)
        this.$store.commit('CHANGE_CITY', city)
        this.keyword = ''
        this.$router.push('/')
      }
    },
    mounted(){
      this.$nextTick(()=>{
        this.scroll = new Bscroll(this.$refs.search)
      })
    },
    computed: {
      nocity (){
        return !this.list.length
      }
    },
    watch: {
      keyword (){
        if (this.timer) {
          clearTimeout(this.timer)
        }
        if (!this.keyword) {
          this.list = []
          return
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.allCity) {
            this.allCity[i].forEach((value) => {
              if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                result.push(value)
              }
            })
          }
          this.list = result
        }, 100)
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import '~@S/varibles.styl'
  .search
    background: $bgColor
    line-height: .72rem
    height: .72rem
    width: 100%
    text-align: center
    .search-input
      background: #fff
      width: 95%
      height: .58rem
      line-height: .58rem
      border-radius: .1rem
      text-align: center
      color: #666
      padding: 0 .1rem
      box-sizing: border-box
  .search-content
    overflow: hidden
    position: absolute
    left: 0
    top: 1.55rem
    right: 0
    bottom: 0
    z-index: 1
    background: #eee
    .search-item
      line-height: .54rem
      padding-left: .1rem
      color: #666
      background: #fff
</style>
